import { Component, OnInit, ElementRef, Renderer2, AfterContentChecked } from '@angular/core';
import {
  ModalController,
  NavController,
} from '@ionic/angular';
import { Subscription, Observable } from 'rxjs';
import { DataService } from '@services/data.service';
// import { DevicePage } from './../../device/device';
import { RoomVideoModal } from '@modals/room-video/room-video';
import { DeviceVideoModal } from '@modals/device-video/device-video';
import { CacheService } from '@services/cache.service';
import { ActivatedRoute } from '@angular/router';
import { EmitService } from '@services/emit.service';

@Component({
  selector: 'room',
  templateUrl: 'page.html',
  styleUrls: ['room.scss']
})
export class RoomPage implements OnInit, AfterContentChecked {
  subscription: Subscription;
  projectId;
  deviceSysId;
  areaName;
  sysName;
  roomGroups;             // 该系统的所有房间
  selectedRoomIndex = 0;
  deviceTypeGroups;
  autoScrollInterval = null;
  areaParams = [];       // 房间参数
  deviceTypeParams = []; // 设备类型参数
  roomList = [];
  rooms = { list: this.roomList, aim: 0 };
  roomModes = [];       // 选中房间的设备类型及设备
  alarmList = [];
  videoList = [];     // 房间区域摄像头
  deviceVideoList;   // 设备区域摄像头
  roomState = [];       // 房间状态，中间那五个图标
  paramsCodes = [1, 3, 5, 6, 9]  // 页面所需显示的实时数据
  deviceParams;      // 设备类型参数

  loopInterval = null;
  wordInterval = null;
  refreshInterval = null;
  Interval
  constructor(
    public navCtrl: NavController,
    public renderer: Renderer2,
    public el: ElementRef,
    public dataservice: DataService,
    private modalCtrl: ModalController,
    private cacheService: CacheService,
    private activatedRoute: ActivatedRoute,
    private emitService: EmitService,

  ) {
    this.roomGroups = this.emitService.roomGroup.roomGroup;
    this.projectId = this.cacheService.currentProject.projectId ? this.cacheService.currentProject.projectId : 0;
    this.deviceSysId = this.emitService.roomGroup.deviceSysId ? parseInt(this.emitService.roomGroup.deviceSysId, 10) : 0;
    this.sysName = this.emitService.roomGroup.sysName ? this.emitService.roomGroup.sysName : '';
    this.selectedRoomIndex = this.emitService.roomGroup.roomIndex;
  }

  ngOnInit() {
    this.roomGroups = this.emitService.roomGroup.roomGroup;
    this.initNav();
  }

  ngAfterContentChecked() {
    this.toResult();
  }

  ionViewWillEnter() {
    this.wordInterval = setInterval(() => {
      this.toResult();
    }, 10)
    this.Interval = this.refreshInterval;
    this.getRoomParams(this.roomGroups[this.selectedRoomIndex].areaId, this.deviceSysId);
    this.Interval = setInterval(() => {
      this.getRoomParams(this.roomGroups[this.selectedRoomIndex].areaId, this.deviceSysId);
    }, 10000)
  }

  ionViewWillLeave() {
    if (this.Interval) {
      clearInterval(this.Interval);
    }
    if (this.wordInterval) {
      clearInterval(this.wordInterval);
    }
  }

  autoScroll(len) {
    const step = -90;
    let top = 1;
    const ele = this.el.nativeElement.querySelector('.Text-init');
    if (this.autoScrollInterval) {
      clearInterval(this.autoScrollInterval);
      this.renderer.setStyle(ele, 'transition', 'unset');
      this.renderer.setStyle(ele, 'top', 0 + 'px');
    }
    this.autoScrollInterval = setInterval(() => {
      if (top < len) {
        this.renderer.setStyle(ele, 'top', top * step + 'px');
        if (top === 1) {
          this.renderer.setStyle(ele, 'transition', 'top 1s');
        }
        top++;
      } else {
        top = 0;
        this.renderer.setStyle(ele, 'transition', 'unset');
      }
    }, 2000);
  }

  roomChange(index) {
    this.setRoom(index);
  }

  initNav() {
    if (this.roomGroups) {
      for (let j = 0; j < this.roomGroups.length; j++) {
        // 上一个页面改变了length,导致length并非数组真是长度
        if (!this.roomGroups[j]) { break; }
        this.roomList.push({ RoomName: this.roomGroups[j].areaName });
      }
      this.rooms = { list: this.roomList, aim: this.selectedRoomIndex };
      this.areaName = this.roomList[this.selectedRoomIndex].RoomName;
    }
  }

  // 获取房间设备类型参数
  getRoomParams(areaId, deviceSysId) {
    this.dataservice.getRooms(areaId, deviceSysId).subscribe(res => {
      // 根据数据类型分组
      // 1.设备，2.房间参数，3.设备参数
      const device = [];
      const roomParams = [];
      const deviceParams = [];
      for (const data of res.data.datas) {
        switch (data.dataType) {
          case 1:
            device.push(data);
            break;
          case 2:
            roomParams.push(data);
            break;
          case 3:
            deviceParams.push(data);
            break;
        }
      }
      this.getDeviceParams(res.data.datas, device, roomParams, deviceParams);
      // this.Interval = setInterval(() => {
      //   this.getDeviceParams(res.data.datas, device, roomParams, deviceParams);
      // }, 10000);
      this.toResult();
    });
  }

  // 获取对应系统下的设备及参数
  getDeviceParams(datas, device, roomParams, deviceParams) {
    console.log(datas)
    for (const data of datas) {
      data.alarmInfo = null;
      data.alarmLevel = null;
    }
    this.getVideoList(this.roomGroups[this.selectedRoomIndex].areaId);
    this.dealParams(datas, device, deviceParams).subscribe(data => {
      // 获取房间参数
      this.getRoomsParams(roomParams).subscribe(res => {
        console.log('房间参数', res)
        this.areaParams = res;
      })

      // 获取告警信息
      this.getAlarmlist().subscribe(res => {
        this.alarmList = res;
        for (const item of this.alarmList) {
          item.deviceValueLastTime = item.deviceValueLastTime.substr(0, item.deviceValueLastTime.length - 4);
        }
        this.autoScroll(this.alarmList.length);
      })
      if (data) {
        this.areaName = data.areaName;
        this.WordResult(data.deviceTypes);
        this.roomModes = data.deviceTypes;
        this.roomModes.sort(function (a, b) {
          return a.deviceTypeId - b.deviceTypeId;
        });
        console.log('最终房间数据', this.roomModes);
      }
    });
  }

  // 获取房间设备告警
  getAlarmlist(): Observable<any> {
    return new Observable(responseObserver => {
      this.dataservice.getRoomAlarmlist(this.deviceSysId, this.projectId, this.roomGroups[this.selectedRoomIndex].areaId).subscribe(res => {
        responseObserver.next(res.data);
        responseObserver.complete();
      });
    });
  }

  // 获取房间参数
  getRoomsParams(params): Observable<any> {
    return new Observable(responseObserver => {
      let deviceIdAndDeviceParam = [];
      const arr = [];
      for (const datas of params) {
        for (const data of datas.deviceParameters) {
          arr.push({ deviceId: datas.deviceId, deviceParameterCode: data.parameterCode });
          deviceIdAndDeviceParam = arr;
        }
      }
      this.dataservice.getDeviceRealParams(deviceIdAndDeviceParam).subscribe(res => {
        for (const datas of params) {
          for (const data of res.data.datas) {
            if (data.deviceId === datas.deviceId) {
              for (const item of datas.deviceParameters) {
                if (data.deviceParameterCode === item.parameterCode) {
                  Object.assign(item, data);
                }
              }
            }
          }
        }
        this.excludeCommunicateStatus(params, null)
        responseObserver.next(params);
        responseObserver.complete();
      });
    });
  }

  // 获取设备类型参数
  getDeviceTypeParams(deviceParams): Observable<any> {
    return new Observable(responseObserver => {
      let deviceIdAndDeviceParam = [];
      const arr = [];
      for (const datas of deviceParams) {
        for (const data of datas.deviceParameters) {
          arr.push({ deviceId: datas.deviceId, deviceParameterCode: data.parameterCode });
          deviceIdAndDeviceParam = arr;
        }
      }
      this.dataservice.getDeviceRealParams(deviceIdAndDeviceParam).subscribe(res => {
        for (const datas of deviceParams) {
          for (const data of res.data.datas) {
            if (data.deviceId === datas.deviceId) {
              for (const item of datas.deviceParameters) {
                if (data.deviceParameterCode === item.parameterCode) {
                  Object.assign(item, data);
                }
              }
            }
          }
        }
        this.excludeCommunicateStatus(null, deviceParams)
        responseObserver.next(deviceParams);
        responseObserver.complete();
      });
    });
  }

  // 业务数据处理
  dealParams(datas, data, deviceParams): Observable<any> {
    return new Observable(responseObserver => {
      // 获取设备对应的设备参数
      if (!data) {
        return null;
      }

      // 先将告警放到对应的设备下
      this.dataservice.getRoomAlarmlist(this.deviceSysId, this.projectId, this.roomGroups[this.selectedRoomIndex].areaId).subscribe(res => {
        for (let k = 0; k < res.data.length; k++) {
          let device;
          device = this.findDevice(res.data[k].deviceTypeId, res.data[k].deviceId, datas);
          console.log(device)
          if (device) {
            if (!device.alarmInfo) {
              device.alarmInfo = [];
            }
            device.alarmInfo.push(res.data[k]);
            for (let m = 0; m < device.deviceParameters.length; m++) {
              device.deviceParameters[m].alarmInfo = [];
              for (let n = 0; n < device.alarmInfo.length; n++) {
                if (device.deviceParameters[m].parameterCode === device.alarmInfo[n].deviceParameterCode) {
                  device.deviceParameters[m].alarmInfo.push(device.alarmInfo[n]);
                }
              }
            }
            device.alarmLevel = Math.max(res.data[k].alarmLevel, device.alarmLevel || 0);
          }
        }

        let newData;
        newData = {};
        newData.areaId = this.roomGroups[this.selectedRoomIndex].areaId;
        newData.areaName = this.roomGroups[this.selectedRoomIndex].areaName;
        newData.areaParams = [];
        newData.deviceTypeParams = [];
        let deviceIdAndDeviceParam = [];
        const arr = [];
        // 获取设备实时数据
        for (const items of data) {
          for (const item of this.paramsCodes) {
            const obj = { deviceId: items.deviceId, deviceParameterCode: item };
            arr.push(obj);
          }
          deviceIdAndDeviceParam = arr;
        }
        this.dataservice.getDeviceRealParams(deviceIdAndDeviceParam).subscribe(res => {
          for (const items of data) {
            if (items.dataType === 1) {
              items.deviceParameters = [];
            }
            for (const item of res.data.datas) {
              if (item.deviceId === items.deviceId) {
                items.deviceParameters.push(item)
              }
            }
          }
          // 获取设备参数
          newData.deviceTypes = this.getGroup(data);
          this.getDeviceTypeParams(deviceParams).subscribe(res => {
            this.deviceTypeParams = res;
            console.log('获取设备类型参数', this.deviceTypeParams);
            // 获取设备类型参数
            for (let i = 0; i < newData.deviceTypes.length; i++) {
              for (let j = 0; j < this.deviceTypeParams.length; j++) {
                if (newData.deviceTypes[i].parentDeviceTypeId === this.deviceTypeParams[j].parentDeviceTypeId) {
                  newData.deviceTypes[i].deviceTypeParams.push(this.deviceTypeParams[j]);
                }
              }
            }

            console.log('摄像头', this.deviceVideoList)
            // 如果有摄像头设备类型直接分组，没有则添加新分组
            if (this.deviceVideoList && this.deviceVideoList.length) {
              let Num = 0;
              for (let i = 0; i < newData.deviceTypes.length; i++) {
                if (newData.deviceTypes[i].deviceTypeId === 4600) {
                  Num += 1;
                  for (const item of this.deviceVideoList) {
                    newData.deviceTypes[i].devices.push(item);
                  }
                }
              }
              if (!Num) {
                const obj = {
                  deviceTypeName: '摄像头',
                  devices: this.deviceVideoList,
                }
                newData.deviceTypes.push(obj);
              }
            }
            responseObserver.next(newData);
            responseObserver.complete();
          });
        });
      })
    });
  }


  // 按照设备类型分组
  getGroup(data) {
    const map = {};
    const dest = [];
    for (let i = 0; i < data.length; i++) {
      const ai = data[i];
      if (ai.dataType === 1) {
        if (!map[ai.parentDeviceTypeId]) {
          dest.push({
            areaId: ai.areaId,
            areaName: ai.areaName,
            deviceId: ai.deviceId,
            isCamera: ai.isCamera,
            deviceTypeId: ai.deviceTypeId,
            deviceTypeName: ai.deviceTypeName,
            deviceName: ai.deviceName,
            parentDeviceTypeId: ai.parentDeviceTypeId,
            deviceTypeParams: [],
            devices: [this.createDevice(ai)]
          });
          map[ai.parentDeviceTypeId] = ai;
        } else {
          for (let j = 0; j < dest.length; j++) {
            const dj = dest[j];
            if (dj.parentDeviceTypeId === ai.parentDeviceTypeId) {
              dj.devices.push(this.createDevice(ai));
              break;
            }
          }
        }
      }
    }
    return dest;
  }

  createDevice(data) {
    let obj; obj = {};
    obj.deviceId = data.deviceId;
    obj.deviceName = data.deviceName;
    obj.deviceTypeId = data.deviceTypeId;
    obj.isCamera = data.isCamera || null;
    obj.alarmLevel = data.alarmLevel || 0;
    obj.alarmInfo = data.alarmInfo || [];
    obj.runStatus = { value: '', valueName: '' };
    obj.communicateStatus = { value: '', valueName: '' };
    obj.autoStatus = { value: '', valueName: '' };
    obj.cutSwitch = { value: '', valueName: '' };
    obj.disSwitch = { value: '', valueName: '' };
    for (let i = 0; i < data.deviceParameters.length; i++) {
      if (data.deviceParameters[i].deviceParameterCode === 1) {         // 运行状态
        obj.runStatus.value = data.deviceParameters[i].value ? 1 : 0;
        obj.runStatus.valueName = data.deviceParameters[i].valueName;
      } else if (data.deviceParameters[i].deviceParameterCode === 9) {  // 通讯状态
        obj.communicateStatus.value = data.deviceParameters[i].value === 1 || data.deviceParameters[i].value === 0 ? parseInt(data.deviceParameters[i].value, 10) : null;
        obj.communicateStatus.valueName = data.deviceParameters[i].valueName;
      } else if (data.deviceParameters[i].deviceParameterCode === 3) {  // 手自动状态
        obj.autoStatus.value = data.deviceParameters[i].value ? 1 : 0;
        obj.autoStatus.valueName = data.deviceParameters[i].valueName;
      } else if (data.deviceParameters[i].deviceParameterCode === 5) {  // 断路器分合闸状态
        obj.cutSwitch.value = data.deviceParameters[i].value ? 1 : 0;
        obj.cutSwitch.valueName = data.deviceParameters[i].valueName;
      } else if (data.deviceParameters[i].deviceParameterCode === 6) {  // 断路器分合闸状态
        obj.disSwitch.value = data.deviceParameters[i].value ? 1 : 0;
        obj.disSwitch.valueName = data.deviceParameters[i].valueName;
      } {
      }
    }
    obj.deviceParameters = data.deviceParameters;
    return obj;
  }


  setRoom(index) {
    this.selectedRoomIndex = index;
    if (this.Interval) {
      clearInterval(this.Interval);
    }
    this.Interval = this.loopInterval;
    this.getRoomParams(this.roomGroups[this.selectedRoomIndex].areaId, this.deviceSysId);
  }


  // 打开房间视频
  async openRoomVideo() {
    if (this.loopInterval) {
      clearInterval(this.loopInterval);
    }
    this.toVideo();
  }

  async toVideo() {
    const config = {
      title: this.cacheService.currentProject.projectName + this.areaName,
      message: this.areaParams,
      videoList: this.videoList,
      areaId: this.roomGroups[this.selectedRoomIndex].areaId
    };
    const videoModal = await this.modalCtrl.create({
      component: RoomVideoModal,
      componentProps: { config: config }
    });
    await videoModal.present();
  }

  async toDeviceVideo(data) {
    const config = {
      title: this.cacheService.currentProject.projectName + this.areaName + data.cameraName,
      message: this.areaParams,
      deviceVideoList: [data],
      areaId: this.roomGroups[this.selectedRoomIndex].areaId,
      deviceId: data.deviceId
    };
    const VideoModal = await this.modalCtrl.create({
      component: DeviceVideoModal,
      componentProps: { config: config }
    });
    await VideoModal.present();
  }

  getVideoList(areaId) {
    this.dataservice.getRoomVideoList(areaId).subscribe(res => {
      const cameraOne = [];
      const cameraTwo = [];
      for (let i = 0; i < res.data.datas.length; i++) {
        if (res.data.datas[i].position === 1) {
          cameraOne.push(res.data.datas[i])
        } else if (res.data.datas[i].position === 2) {
          cameraTwo.push(res.data.datas[i])
        }
      }
      this.deviceVideoList = cameraOne;
      this.videoList = cameraTwo;
    });
  }

  toDevicePage(device, index, devices) {
    const data = {
      projectId: this.projectId,
      deviceID: device.deviceId,
      areaName: this.areaName,
      devices: devices,
      deviceIndex: index
    };
    this.emitService.deviceParams = data;
    this.navCtrl.navigateForward(['tabs/home/DevicePage'], {
      queryParams: data
    }
    );
  }

  toPage() {
    this.navCtrl.navigateForward(['']);
  }

  // 房间参数，设备类型参数不要通讯状态
  excludeCommunicateStatus(roomData, deviceData) {
    console.log('需要处理的参数', roomData, deviceData)
    // 移除房间参数
    if (roomData && roomData.length) {
      for (let i = 0; i < roomData.length; i++) {
        for (let j = roomData[i].deviceParameters.length - 1; j >= 0; j--) {
          if (roomData[i].deviceParameters[j].parameterCode === 9) {
            if (roomData[i].deviceParameters[j].value === 0 || roomData[i].deviceParameters[j].valueName === '离线') {
              for (let k = roomData[i].deviceParameters.length - 1; k >= 0; k--) {
                roomData[i].deviceParameters[k].value = '-';
                roomData[i].deviceParameters[k].valueName = '-';
                if (roomData[i].deviceParameters[k].parameterCode === 9) {
                  roomData[i].deviceParameters.splice(k, 1);
                }
              }
            } else {
              roomData[i].deviceParameters.splice(j, 1);
            }
          } else if (roomData[i].deviceParameters[j].parameterCode === 1) { // 启停状态
            roomData[i].deviceParameters.splice(j, 1);
          } else if (roomData[i].deviceParameters[j].parameterCode === 3) { // 手自动状态
            roomData[i].deviceParameters.splice(j, 1);
          }
        }
      }
    }

    // 移除设备类型参数通讯状态
    if (deviceData && deviceData.length) {
      for (let i = 0; i < deviceData.length; i++) {
        for (let k = deviceData[i].deviceParameters.length - 1; k >= 0; k--) {
          if (deviceData[i].deviceParameters[k].parameterCode === 9) {      // 通讯状态
            deviceData[i].isRun = deviceData[i].deviceParameters[k].value;
            deviceData[i].deviceParameters.splice(k, 1);
          } else if (deviceData[i].deviceParameters[k].parameterCode === 1) { // 启停状态
            deviceData[i].deviceParameters.splice(k, 1);
          } else if (deviceData[i].deviceParameters[k].parameterCode === 3) { // 手自动状态
            deviceData[i].deviceParameters.splice(k, 1);
          }
        }
      }
    }
    return null;
  }

  findDevice(deviceTypeId, deviceId, data) {
    for (let i = 0; i < data.length; i++) {
      if (data[i].deviceTypeId === deviceTypeId && data[i].deviceId === deviceId) {
        return data[i];
      }
    }
  }

  // 文字处理
  WordResult(word) {
    for (const items of word) {
      for (const item of items.devices) {
        if (item.deviceName && item.deviceName.length >= 9) {
          item.deviceName = item.deviceName.substring(0, 8) + '...';
        } else if (item.cameraName && item.cameraName.length >= 9) {
          item.deviceName = item.cameraName.substring(0, 8) + '...';
        }
      }
    }
  }

  // 控制单位显示是否换行
  // 判断文字与单位是否超过显示行
  toResult() {
    if (this.el.nativeElement.querySelectorAll('.text')) {
      const elText = this.el.nativeElement.querySelectorAll('.text');
      for (let i = 0; i < elText.length; i++) {
        // 暂时先判断最多两行情况
        if (elText[i].children[0].offsetHeight) {

          if (elText[i].children[0].innerHTML.length >= (Math.ceil(elText[i].children[0].offsetHeight / 16) * 8 - 4)) {
            // 判断单位宽度与文字宽度是否大于总宽度
            if (elText[i].children[2]) {
              if (elText[i].offsetWidth < elText[i].children[0].offsetWidth +
                elText[i].children[1].offsetWidth + elText[i].children[2].offsetWidth) {
                if (elText[i].children[0]) {
                  this.renderer.setStyle(elText[i].children[0], 'display', 'block');
                }
              } else {
                if (elText[i].children[1]) {
                  this.renderer.setStyle(elText[i].children[1], 'display', 'inline-block');
                }
              }
            } else {
              if (elText[i].children[1]) {
                if (elText[i].offsetWidth < elText[i].children[0].offsetWidth + elText[i].children[1].offsetWidth) {
                  if (elText[i].children[0]) {
                    this.renderer.setStyle(elText[i].children[0], 'display', 'block');
                  }
                } else {
                  if (elText[i].children[1]) {
                    this.renderer.setStyle(elText[i].children[1], 'display', 'inline-block');
                  }
                }
              }
            }
          }

        }
      }
    }
  }

  goBack() {
    this.navCtrl.pop();
  }

}
